package com.guigu.springcloud.controller;

import com.guigu.springcloud.entities.CommonResult;
import com.guigu.springcloud.entities.Payment;
import com.guigu.springcloud.lib.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * @Date 2021/7/23 10:54
 * @Created by wangle
 * @Description
 */
@RestController
@Slf4j
public class OrderController {
    @Resource
    public LoadBalancer loadBalancer;

    @Resource
   private DiscoveryClient  discoveryClient;
//  public  static  final  String payment_Url="http://localhost:8001";
public  static  final  String payment_Url="http://CLOUD-PAYMENT-SERVICE";
    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/consumer/payment/creat")
    public CommonResult create(Payment payment){

        return  restTemplate.postForObject(payment_Url+"/payment/creat",payment,CommonResult.class);

    }

    @GetMapping("/consumer/payment/get/{id}")
    public  CommonResult<Payment> getpayment(@PathVariable("id") Long id){
        return  restTemplate.getForObject(payment_Url+"/payment/get/"+id,CommonResult.class);
    }


    @GetMapping("/consumer/payment/getforentity/{id}")
    public  CommonResult<Payment> getpaymententity(@PathVariable("id") Long id){

        ResponseEntity<CommonResult> entity=restTemplate.getForEntity(payment_Url+"/payment/get/"+id,CommonResult.class);
        if(entity.getStatusCode().is2xxSuccessful()){

            return  entity.getBody();
        }else {
            return  new CommonResult<>(244,"操作失败");

        }

    }

    @GetMapping("/consumer/payment/lb")
    public  String getpaymentlb(){
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if(instances==null|| instances.size()<=0){

            return  null;
        }

        ServiceInstance serviceInstance=loadBalancer.instances(instances);
        URI uri=serviceInstance.getUri();
        return  restTemplate.getForObject(uri+"/payment/lb",String.class);

    }



    // ====================> zipkin+sleuth
    @GetMapping("/consumer/payment/zipkin")
    public String paymentZipkin()
    {
        String result = restTemplate.getForObject("http://localhost:8001"+"/payment/zipkin/", String.class);
        return result;
    }



}
